package ntd.util.frame.task.handle.fm.remote;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.modular.iot.bo.IotData;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.task.handle.fm.remote.bo.ProPlatSiteInfo;
import ntd.util.frame.task.handle.fm.remote.bo.RemoteFmProvincePlatformInBo;
import ntd.util.frame.task.handle.fm.remote.bo.RemoteFmProvincePlatformOutBo;

import java.util.List;

/**
 * 河南省环保厅平台对接
 */
public class RemoteFmProvincePlatform {

    // 根路径
    private static final String URL = "http://10.41.109.99:8061";

    /**
     * 历史数据接口
     * @return
     */
    public static List<IotData> listHistoryHourData(RemoteFmProvincePlatformInBo remoteFmProvincePlatformInBo) {
        JSONArray dataArr = JSONUtil.parseArray(exeRequest("/Api/WDM/HourDataApi/GetHistoryHourDataListForProvider", remoteFmProvincePlatformInBo));
        return CollStreamUtil.toList(dataArr, o -> IotData.transformProvincePlatformData(JSONUtil.parseObj(o)));
    }

    /**
     * 基站信息接口
     * @return 基站信息列表
     */
    public static List<ProPlatSiteInfo> siteInfo() {
        Object res = exeRequest("/Api/WDM/HourDataApi/GetStationInfoDataListForProvider", null);
        List<ProPlatSiteInfo> proPlatSiteInfos = JSONUtil.toList(JSONUtil.toJsonStr(res), ProPlatSiteInfo.class);
        return proPlatSiteInfos;
    }

    /**
     * 执行请求
     * @param api
     * @param inBo
     * @return
     */
    private static Object exeRequest(String api, Object inBo) {
        HttpRequest httpRequest = initRequest(api);
        if (ObjectUtil.isNotNull(inBo)) {
            httpRequest.body(JSONUtil.toJsonStr(inBo));
        }
        HttpResponse response = httpRequest.execute();
        RemoteFmProvincePlatformOutBo remoteFmProvincePlatformOutBo = JSONUtil.toBean(response.body(), RemoteFmProvincePlatformOutBo.class);
        if (new Integer(2).equals(remoteFmProvincePlatformOutBo.getState())) {
            throw new ComException("省平台接口返回失败[{}]", remoteFmProvincePlatformOutBo.getMessage());
        }
        return remoteFmProvincePlatformOutBo.getData();
    }


    private static HttpRequest initRequest(String api) {
        HttpRequest post = HttpUtil.createPost("http://10.41.109.99:8061/" + api);
        post.header("Authorization", "bc9be969a2cc49689ee0eda61acabd37");
        return post;
    }

}
